package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.*;
import com.leoman.entity.*;
import com.leoman.exception.NoDataException;
import com.leoman.exception.ParamErrorException;
import com.leoman.service.CircleService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.QiNiuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * CircleServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 3:57.
 */
@Service
public class CircleServiceImpl implements CircleService {

    @Autowired
    private CircleDao circleDao;

    @Autowired
    private PraiseDao praiseDao;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private ImageDao imageDao;

    @Override
    public List<Circle> findAll() {
        return circleDao.findAll();
    }

    @Override
    public Page<Circle> find(int pageNum, int pageSize) {
        return circleDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Circle> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Circle getById(int id) {
        return circleDao.findOne(id);
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        Circle circle = circleDao.findOne(id);

        List<String> tempUrl = new ArrayList<>();
        List<Image> imageList;

        // 删除该草丛的所有评论
        List<Comment> commentList = commentDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_CIRCLE);
        for (Comment comment : commentList) {
            // 删除评论中的图片
            imageList = imageDao.findListByParams(comment.getId(), Constant.SOURCE_TYPE_COMMENT);
            for (Image image : imageList) {
                tempUrl.add(image.getUrl());
                imageDao.delete(image);
            }
            System.out.println("");
            // 删除评论中的语音文件
            if (comment.getVoiceTime() > 0) {
                tempUrl.add(comment.getContent());
            }

            commentDao.delete(comment.getId());
        }

        // 删除该草丛的所有收藏
        List<UserCollect> collectList = userCollectDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_CIRCLE);
        for (UserCollect userCollect : collectList) {
            userCollectDao.delete(userCollect);
        }

        // 删除该草丛的所有点赞
        List<Praise> praiseList = praiseDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_CIRCLE);
        for (Praise praise : praiseList) {
            praiseDao.delete(praise);
        }

        tempUrl.add(circle.getCover1());
        tempUrl.add(circle.getCover2());
        tempUrl.add(circle.getCover3());

        circleDao.delete(id);

        for (String url : tempUrl) {
            QiNiuUtils.delete(url);
        }
    }

    @Override
    public Circle create(Circle circle) {
        return circleDao.save(circle);
    }

    @Override
    public Circle update(Circle circle) {
        return circleDao.save(circle);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<Circle> iPageForApp(final Integer userId, final Integer isMe, final String tagName, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);

        Page<Circle> page = circleDao.findAll(new Specification<Circle>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Circle> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (null != userId && null != isMe && isMe.equals(Constant.USER_STATUS_YES)) {
                    predicateList.add(cb.equal(root.get("user").get("id").as(Integer.class), userId));
                } else {
                    predicateList.add(cb.equal(root.get("isDraft").as(Integer.class), Constant.USER_STATUS_NO));
                }

                if (StringUtils.isNotBlank(tagName)) {
                    predicateList.add(cb.equal(root.get("labels").as(String.class), tagName));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "isAdmin", "isTop", "id"));

        for (Circle circle : page.getContent()) {
            changeCircleInfo(circle, null == isMe || isMe.equals(Constant.USER_STATUS_NO) ? userId : null);
        }

        return page;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Page<Circle> iPageForAppCollect(Integer userId, String tagName, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        PageRequest pageRequest = new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "id");

        final Page<UserCollect> userCollectPage = userCollectDao.iPageByUserId(userId, Constant.SOURCE_TYPE_CIRCLE, pageRequest);

        List<Circle> list = new ArrayList<>();

        for (UserCollect userCollect : userCollectPage.getContent()) {
            list.add(circleDao.findOne(userCollect.getSourceId()));
        }

        Page<Circle> circlePage = new PageImpl(list, pageRequest, userCollectPage.getTotalElements());

        for (Circle circle : circlePage.getContent()) {
            changeCircleInfo(circle, userId);
        }

        return circlePage;
    }

    @Override
    @Transactional
    public void addCircleInfo(Boolean isAdmin,
                              Integer tempId,
                              Integer userId,
                              String title,
                              String content,
                              String synopsis,
                              String labels,
                              Integer isDraft,
                              MultipartRequest multipartRequest) throws ParamErrorException {
        MultipartFile cover1 = multipartRequest.getFile("cover1");
        MultipartFile cover2 = multipartRequest.getFile("cover2");
        MultipartFile cover3 = multipartRequest.getFile("cover3");

        Circle circle;

        if (null == tempId) {
            circle = new Circle();
        } else {
            circle = circleDao.findOne(tempId);
        }

        if (isAdmin) {
            Circle circleByAdmin = circleDao.iFindOneWithAdmin();

            if (null != circleByAdmin) {
                deleteById(circleByAdmin.getId());
            }
        } else {
            if (null == userId || null == isDraft) {
                throw new ParamErrorException();
            }

            User user = new User();
            user.setId(userId);

            circle.setUser(user);
        }

        circle.setTitle(title);

        if (null != cover1 && cover1.getSize() > 0) {
            QiNiuUtils.delete(circle.getCover1());

            circle.setCover1(QiNiuUtils.upload(cover1));
        }

        if (null != cover2 && cover2.getSize() > 0) {
            QiNiuUtils.delete(circle.getCover2());

            circle.setCover2(QiNiuUtils.upload(cover2));
        }

        if (null != cover3 && cover3.getSize() > 0) {
            QiNiuUtils.delete(circle.getCover3());

            circle.setCover3(QiNiuUtils.upload(cover3));
        }

        circle.setContent(content);
        circle.setSynopsis(synopsis);
        circle.setLabels(labels);
        circle.setIsAdmin(isAdmin ? Constant.USER_STATUS_YES : Constant.USER_STATUS_NO);
        circle.setIsDraft(isDraft);

        if (isDraft.equals(Constant.USER_STATUS_YES)) {
            Circle tempCircle = circleDao.iFindDraftByUserId(userId);
            deleteById(tempCircle.getId());
        }

        circleDao.save(circle);

        // 保存草丛图片
        List<MultipartFile> list = multipartRequest.getFiles("image");

        Image image;
        for (MultipartFile file : list) {
            if (null != file && file.getSize() > 0) {
                image = new Image();
                image.setUrl(QiNiuUtils.upload(file));
                image.setSourceId(circle.getId());
                image.setSourceType(Constant.SOURCE_TYPE_CIRCLE);

                imageDao.save(image);
            }
        }
    }

    @Override
    public Circle iFindDraftByUserId(Integer userId) throws ParamErrorException, NoDataException {
        Circle circle = circleDao.iFindDraftByUserId(userId);

        circle.setImageList(imageDao.findListByParams(circle.getId(), Constant.SOURCE_TYPE_CIRCLE));

        return circle;
    }

    @Override
    public Page<Circle> pageByParams(final String userName, final String startTime, final String endTime, Integer pageNum, Integer pageSize) {
        return circleDao.findAll(new Specification<Circle>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Circle> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (StringUtils.isNotBlank(userName)) {
                    predicateList.add(cb.like(root.get("user").get("nickName").as(String.class), "%" + userName + "%"));
                }

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        System.out.println("...");
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        System.out.println("...");
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                predicateList.add(cb.equal(root.get("isDraft").as(Integer.class), Constant.USER_STATUS_NO));

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "isAdmin", "isTop", "id"));
    }

    @Override
    public Integer toTop(Integer circleId) {
        try {
            Circle topCircle = circleDao.iFindOneWithTop();
            Circle circle = circleDao.findOne(circleId);

            if (null != topCircle && circleId.equals(topCircle.getId())) {
                return -1;
            }

            if (null != topCircle) {
                topCircle.setIsTop(Constant.USER_STATUS_NO);
                circleDao.save(topCircle);
            }

            circle.setIsTop(Constant.USER_STATUS_YES);
            circleDao.save(circle);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public Integer batchDelete(String ids) {
        try {
            Integer[] circleIds = JsonUtil.json2Obj(ids, Integer[].class);
            System.out.println("  ");
            for (Integer circleId : circleIds) {
                deleteById(circleId);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 加载兴趣圈附属信息
     *
     * @param circle 兴趣圈信息
     * @param userId 用户ID
     */
    private void changeCircleInfo(Circle circle, Integer userId) {
        if (null == userId) {
            circle.setIsPraise(Constant.USER_STATUS_NO);
            circle.setIsCollect(Constant.USER_STATUS_NO);
        } else {
            circle.setIsPraise(null == praiseDao.findOneByParams(userId, circle.getId(), Constant.SOURCE_TYPE_CIRCLE) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
            circle.setIsCollect(null == userCollectDao.findOneByParams(userId, circle.getId(), Constant.SOURCE_TYPE_CIRCLE) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
        }

        Integer praiseNum = praiseDao.findListBySourceIdAndType(circle.getId(), Constant.SOURCE_TYPE_CIRCLE).size();
        Integer commentNum = commentDao.findListBySourceIdAndType(circle.getId(), Constant.SOURCE_TYPE_CIRCLE).size();

        circle.setPraiseNum(praiseNum * 2 + commentNum);
        circle.setCommentNum(commentNum);
        circle.setCollectNum(userCollectDao.findListBySourceIdAndType(circle.getId(), Constant.SOURCE_TYPE_CIRCLE).size());
        circle.setContent(circle.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));

        List<Image> imageList = new ArrayList<>();

        if (circle.getIsAdmin().equals(Constant.USER_STATUS_NO)) {
            circle.setUserId(circle.getUser().getId());
            circle.setAvatar(circle.getUser().getAvatar());
            circle.setNickName(circle.getUser().getNickName());

            imageList = imageDao.findListByParams(circle.getId(), Constant.SOURCE_TYPE_CIRCLE);
        } else {
            Image image;
            if (StringUtils.isNotBlank(circle.getCover1())) {
                image = new Image();
                image.setUrl(circle.getCover1());

                imageList.add(image);
            }

            if (StringUtils.isNotBlank(circle.getCover2())) {
                image = new Image();
                image.setUrl(circle.getCover2());

                imageList.add(image);
            }

            if (StringUtils.isNotBlank(circle.getCover3())) {
                image = new Image();
                image.setUrl(circle.getCover3());

                imageList.add(image);
            }
        }

        circle.setImageList(imageList);
    }
}